<?php

class clientsFormWidgetActions extends myFrontendAction
{    /**   * This method sends the request   * to receive a list of addresses to display in the autocomplete field   */  public function executeGetAddress(sfRequest $request)  {    $this->setLayout(false);
    $this->qwerty = array();
    
    if(($xml = $this->getXmlString($request->getParameter('term'), 'O9eRt8rhL'))) {
      if(($response = $this->sendRequest($xml))) {
        $this->qwerty = $this->parseXml($response);
      }
    }
  }
  
  
  /**
   * This method send a XML string via POST using cURL
   */
  protected function sendRequest($xml)
  {
    $client = curl_init();

    curl_setopt_array($client, array(
      CURLOPT_HEADER         => false,
      CURLOPT_POST           => true,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POSTFIELDS     => $xml,
      CURLOPT_URL            => 'http://79.125.56.78/digilahendus/ws/',
      CURLOPT_HTTPHEADER     => array(
        'Content-Type: text/xml; charset=utf-8',
        'Content-Length: ' . strlen($xml)
      )
    ));


    if(($response = curl_exec($client))) {
      return $response;
    } else return false;
  }
  
  
  /**
   * Make XML string to use it in the request
   */
  protected function getXmlString($address, $auth)
  {
    //  XML File
    return <<<XML
      <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:dig="http://post.ee/digilahendus">
       <soapenv:Header/>
       <soapenv:Body>
          <dig:SingleAddress2_5Request authPhrase="{$auth}">
             <dig:aadress>{$address}</dig:aadress>
             <dig:ainult_korrektsed>false</dig:ainult_korrektsed>
          </dig:SingleAddress2_5Request>
       </soapenv:Body>
    </soapenv:Envelope>

XML;
  }
  
  
  /**
   * Parse response XML file
   */
  private function parseXml($xml)
  {
    $document = new DOMDocument();
    $elements = array();
    
    if($document->loadXML($xml)) {
      $components = $document->getElementsByTagName('aadressKomponent');
      
      if($components->length) {
        foreach($components as $j => $component) {
          $address = $component->getElementsByTagName('aadress');
          $zipCode = $component->getElementsByTagName('sihtnumber');
          
          if($address->length === 1) {
            $elements[$j] = $address->item(0)->nodeValue;
            
            if($zipCode->length === 1) {
              $elements[$j] .= ', ' . $zipCode->item(0)->nodeValue;
            }
          }
        }
      }
    }
    
    return $elements;
  }
}